package com.fingard.dsp.bank.directbank.tjcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

public class TJCB01Transaction extends TJCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        StringBuilder message = new StringBuilder();
        int succeCount = 0;//查询的总条数
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //按自然月循环查询
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                //每次请求返回的数据条数
                int tmpCount = 0;
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                TJCB01Header tjcb01Header = new TJCB01Header();
                tjcb01Header.transName = "B2eQueryAllTransInfo";
                tjcb01Header.clientTime = Format.DateTime2Format.format(new Date());
                tjcb01Header.batchID = p_req7516.reqHeader.transSeqID;
                tjcb01Header.transCount = "1";
                //发银行报文的XML对象
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHeader(xmlWriter, tjcb01Header);
                xmlWriter.writeStartElement("RequestBody");
                xmlWriter.writeStartElement("RequestRecord");
                //账号
                xmlWriter.writeElementString("AcctNo", p_req7516.actNum);
                xmlWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("EndDate", Format.Date8Format.format(tmpCalendarTo.getTime()));
                //转账类型 0-全部 1-行内转账 2-跨行转账 3-快速跨行转账
                xmlWriter.writeElementString("TransType", "0");
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req7516.reqHeader.transType, p_req7516.reqHeader.transType);

                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmprspcode = tmpBkReader.getFirstText("/transaction/RespondHeader/respondCode");
                        String tmprspmsg = tmpBkReader.getFirstText("/transaction/RespondHeader/respondInfo");
                        if (tmprspcode != null && "0000".equals(tmprspcode)) {
                            String totalCountStr = tmpBkReader.getFirstTextNotNull("/transaction/RespondBody/RespondRecord/TotalCount");
                            int totalCount = StringHelper.changeStrToNum(totalCountStr);
                            if (totalCount > 0) {
                                while (tmpBkReader.read("/transaction/RespondBody/RespondRecord/itemsSet/item")) {
                                    succeCount++;
                                    tmpCount++;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    XElement tmpRecord = tmpBkReader.readedXElement;
                                    tmpRetDetail.actNum = tmpRecord.getSingleText("outAcno");
                                    tmpRetDetail.recAccNum = tmpRecord.getSingleText("inAcno");//收方账号
                                    tmpRetDetail.recAccName = tmpRecord.getSingleText("inName");//收方户名
                                    tmpRetDetail.recAccBank = tmpRecord.getSingleText("inBank");//收方银行
                                    tmpRetDetail.tranAmt = tmpRecord.getSingleText("transAmt");//交易金额
                                    tmpRetDetail.accBal = tmpRecord.getSingleText("Amount");//账户余额
                                    tmpRetDetail.cdFlag = tmpRecord.getSingleText("OIFlag").equals("D") ? "1" : "2";//借贷标志 D:借 C:贷
                                    String tranDate = tmpRecord.getSingleText("transDate");//交易日期yyyyMMdd
                                    tmpRetDetail.tranDate = DateHelper.convertD8toD10(tranDate);
                                    String tranTime = tmpRecord.getSingleText("transTime");//交易时间yyyyMMddhhmmss
                                    tmpRetDetail.tranTime = DateHelper.convertDateTime(tranTime);
                                    tmpRetDetail.usage = tmpRecord.getSingleText("transNote");
                                    tmpRetDetail.abstr = tmpRecord.getSingleText("note");//摘要（对账码）
                                    nodeAnalysic(tmpRecord, tmpRetDetail, getCharset());//根据配置将 note 分割赋值给对账码和用途
                                    retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                                }
                                if (totalCount != tmpCount) {
                                    message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询总数：").append(totalCount).append(",实际返回数据条数：").append(tmpCount).append("不一致;\r\n");
                                }
                            }
                        } else {
                            message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：").append(tmprspmsg).append(";\r\n");
                        }
                    } else {
                        message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：").append(tmpSbMsg).append(";\r\n");
                    }
                } else {
                    message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：").append(tmpStrRet[1]).append(";\r\n");
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            message.append("查询异常：").append(e.getMessage()).append("\r\n");
            retAts.writeRespInfo(message.toString());
            e.printStackTrace();
            retAts.writeEndWithoutInsertDB();
            return retAts;
        } finally {
            if (message.length() > 0) {
                WriteBankLogLn(message.toString());
            }
        }
        if (succeCount == 0 && message.length() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        } else if (message.length() > 0 && succeCount > 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo(message.toString());
        } else if (succeCount == 0 && message.length() > 0) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(message.toString());
        }
        retAts.writeEndWithoutInsertDB();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }
}
